import jwt
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class JWTAuth:
    """JWT认证服务"""
    
    def __init__(self):
        # JWT密钥（生产环境应该从环境变量获取）
        self.secret_key = "redbook_secret_key_2024"
        self.algorithm = "HS256"
        self.expire_hours = 2  # Token有效期2小时
    
    def generate_token(self, user_id: int, phone: str) -> str:
        """
        生成JWT Token
        
        Args:
            user_id: 用户ID
            phone: 手机号
            
        Returns:
            str: JWT Token
        """
        try:
            # 过期时间
            expire_time = datetime.utcnow() + timedelta(hours=self.expire_hours)
            
            # 载荷数据
            payload = {
                "user_id": user_id,
                "phone": phone,
                "exp": expire_time,
                "iat": datetime.utcnow(),
                "iss": "redbook"
            }
            
            # 生成Token
            token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
            
            logger.info(f"为用户 {user_id} 生成Token成功")
            return token
            
        except Exception as e:
            logger.error(f"生成Token失败: {str(e)}")
            raise e
    
    def verify_token(self, token: str) -> Optional[Dict[str, Any]]:
        """
        验证JWT Token
        
        Args:
            token: JWT Token
            
        Returns:
            Optional[Dict]: 解码后的载荷数据，验证失败返回None
        """
        try:
            # 解码Token
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
            
            # 检查过期时间
            if datetime.utcnow().timestamp() > payload.get("exp", 0):
                logger.warning("Token已过期")
                return None
            
            logger.info(f"Token验证成功，用户ID: {payload.get('user_id')}")
            return payload
            
        except jwt.ExpiredSignatureError:
            logger.warning("Token已过期")
            return None
        except jwt.InvalidTokenError as e:
            logger.warning(f"Token无效: {str(e)}")
            return None
        except Exception as e:
            logger.error(f"Token验证异常: {str(e)}")
            return None
    
    def extract_user_id(self, token: str) -> Optional[int]:
        """
        从Token中提取用户ID
        
        Args:
            token: JWT Token
            
        Returns:
            Optional[int]: 用户ID，提取失败返回None
        """
        payload = self.verify_token(token)
        if payload:
            return payload.get("user_id")
        return None

# 创建全局实例
jwt_auth = JWTAuth()
